package cordova_bridge;

import android.content.Context;

import org.json.JSONArray;
import org.json.JSONException;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class CordovaEvent {


    private Map<String, Set<Callback>> map = new HashMap<>();
    private static CordovaEvent instance;
    private static CordovaEvent getInstance(){
        if(instance == null){
            instance = new CordovaEvent();
        }
        return instance;
    }


    public static void post(Context context, String event, Object ... args){
        Set<Callback> callbacks = getInstance().map.get(event);
        if(callbacks == null){
            return;
        }

        callbacks.forEach(c -> {
            c.onCallback(context, args);
        });
    }


    public static void on(String event, Callback callable){
        Set<Callback> callbacks = getInstance().map.computeIfAbsent(event, k -> new HashSet<>());
        callbacks.add(callable);
    }


    public static void off(String event, Callback callable){
        Set<Callback> callbacks = getInstance().map.computeIfAbsent(event, k -> new HashSet<>());
        callbacks.remove(callable);
    }

    interface Callback {

        void onCallback(Context context, Object ... args);

    }

}
